package states

import (
	"go_server/game_server/dao/count_down_dao"
	"go_server/game_server/event_manager"
	"go_server/game_server/event_manager/event_data/event_impl"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/znet"
)

type BuildRescueApi struct {
	znet.BaseRouter
}

// 完成建筑营救事件
func (*BuildRescueApi) Handle(request ziface.IRequest) {
	msg := &pb.BuildRescueC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	fields := []string{"map_build_ids"}
	row := count_down_dao.GetCountDownByRoleId(roleId, fields)

	mapBuildIds := make([]int32, 0)
	if row != nil && row.MapBuildIds != nil {
		mapBuildIds = row.MapBuildIds
	}

	var update = true

	if len(mapBuildIds) > 0 {
		eventSet := util.NewSet[int32]()
		eventSet.AddValue(mapBuildIds)
		if !eventSet.Contains(msg.MapBuildId) { // 没有完成过
			mapBuildIds = append(mapBuildIds, msg.MapBuildId)
		} else {
			update = false
		}
	} else {
		mapBuildIds = append(mapBuildIds, msg.MapBuildId)
	}

	res := &pb.BuildRescueS2C{
		MapBuildIds: mapBuildIds,
	}

	// 优先返回下行
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_BuildRescue), res)

	if update {
		countDown := count_down_dao.CountDown{
			RoleId:    roleId,
			GuideList: mapBuildIds,
		}
		count_down_dao.UpdateCountDown(&countDown, fields)

		// 发送奖励，策划暂时未配置

		// 创建营救事件
		event_manager.EventManagerObj.FireEventData(event_impl.NewBuildRescueEvent(conn, map[string]int32{
			"id":    msg.MapBuildId, // Map3DConfigBuildId
			"value": 1,              // 营救次数
		}))
	}
}
